package org.grow.pointcolor.tool;

import org.grow.pointcolor.widget.Console;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.swing.*;
import java.awt.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

@Component
public class ScanTask implements Runnable {
    @Autowired
    private Robot robot;
    @Autowired
    private Console console;
    private CountDownLatch countDownLatch;
    private AtomicBoolean loopkey = new AtomicBoolean(true);

    public AtomicBoolean getLoopkey() {
        return loopkey;
    }

    public CountDownLatch getCountDownLatch() {
        return countDownLatch;
    }

    @Override
    public void run() {
        countDownLatch = new CountDownLatch(1);
        while (loopkey.get()) {
            robot.delay(1600);
            Point location = MouseInfo.getPointerInfo().getLocation();
            Color color = robot.getPixelColor(location.x, location.y);
            console.setBackground(color);
            int i = console.getIndex().incrementAndGet();
            console.append(i + " : ");
            console.append(location.toString() + System.lineSeparator() + color.toString() + System.lineSeparator());
            console.setCaretPosition(console.getText().length());
        }
        countDownLatch.countDown();
        console.setBackground(Console.initColor);
    }
}
